package com.wxlsoft.excel.extract;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JProgressBar;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.wxlsoft.excel.core.AbstractProcessor;
import com.wxlsoft.excel.extract.InterfaceManifest.SheetOutput;
import com.wxlsoft.utils.FilesUtli;

public class InterfaceManifestProcessor extends AbstractProcessor {

	private final SheetDataCollector collector = new SheetDataCollector();

	private final String from;
	
	private final String to;
	
	public InterfaceManifestProcessor(String from, String to) {
		this.from = from;
		long millis = System.currentTimeMillis();
		this.to = String.format(to.toString(), millis);
	}
	
	@Override
	protected void write(JProgressBar progress) {
		// 删除历史文件
		FilesUtli.create(new File(to).toPath());
		
		// 写出到 excel 中
		EasyExcel.write(to, SheetOutput.class)
			.sheet("采集")
			.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
			.doWrite(collector.get());
	}

	@Override
	protected void read(JProgressBar progress) {
		// 查询所有接口清单列表
		List<InterfaceManifest> list = EasyExcel.read(from)
				.head(InterfaceManifest.class)
				.sheet("服务接口清单")
				.headRowNumber(2)
				.doReadSync();
		
		// 读取标签页
		try (ExcelReader read = EasyExcel.read(from).build()) {
			final List<ReadSheet> sheets = new LinkedList<>();
			// 迭代清单列表的sheet页
			for (InterfaceManifest manifest : list) {
				ReadSheet sheet = EasyExcel.readSheet(manifest.getName())
						.headRowNumber(5)
						.head(InterfaceManifest.SheetInput.class)
						.registerReadListener(new SheetInputListener(manifest.getName(), progress, collector))
						.build();
				sheets.add(sheet);
			}
			read.read(sheets);
		}
	}

}
